# 汇总
import json
import re
import sys
import cpca
from Matching import AddressMatchingModel, Address
from Train import AddressMatchingModelTrain
import pandas as pd
from util.Timer import timer
import os

current_path = sys.path[0]
DATA_FILE_PATH = os.path.join(current_path, 'file\\')


class AddressMatching():

    @staticmethod
    def once_processing(words: str):
        model = AddressMatchingModel()
        # 训练模型
        # train = AddressMatchingModelTrain()
        # train.train(model)
        model.load()  # 读取模型

        return json.dumps(obj=model.predict(words).__dict__, indent=4, ensure_ascii=False)

    @staticmethod
    def many_times_processing(fileName: str):
        model = AddressMatchingModel()
        model.load()
        address_sum = []
        XZQH = []
        ans_list = []
        df = pd.read_csv(DATA_FILE_PATH + fileName, usecols=[1], encoding='utf8')
        for i in df.values:
            address_sum.append(str(i[0]))
        cur = cpca.transform(address_sum)

        for i in cur.values:
            sumAddr = str(i[0]) + str(i[1]) + str(i[2])
            XZQH.append([sumAddr, i[0], i[1], i[2]])

        for i in range(len(address_sum)):
            ret = Address()
            ret.XZQH = XZQH[i][0]
            for j in range(1, 4):
                try:
                    address_sum[i] = address_sum[i].replace(XZQH[i][j], "")  # 将识别出来的结果从地址里去掉
                    address_sum[i] = address_sum[i].replace(XZQH[i][j][0:-1], "")
                except TypeError:
                    pass

            ret.JLX = model.get_JLX(address_sum[i])
            address_sum[i] = address_sum[i].replace(ret.JLX, "")

            # 提取38号  7幢  三单元  111室等信息
            pattern1 = "[零一二三四五六七八九0-9]+[^零一二三四五六七八九0-9]+"  # 提取 38号  7幢  三单元  111室
            for item in re.findall(pattern1, address_sum[i]):
                typ = model.parseNumberType(item)
                if typ == 1:
                    if ret.houseNumber == "":
                        ret.houseNumber = item
                    else:
                        ret.buildingNumber = item
                elif typ == 2:
                    ret.buildingNumber = item
                elif typ == 3:
                    ret.roomNumber = item
                elif typ == 4:
                    ret.unitNumber = item

            # 到最后街路巷也没有数据则将address去掉这些号作为街道巷
            if ret.JLX == "":
                address_sum[i] = address_sum[i].replace(ret.houseNumber, "")
                address_sum[i] = address_sum[i].replace(ret.buildingNumber, "")
                address_sum[i] = address_sum[i].replace(ret.roomNumber, "")
                address_sum[i] = address_sum[i].replace(ret.unitNumber, "")
                ret.JLX = address_sum[i]

            temp_arr = [ret.XZQH, ret.JLX, ret.houseNumber, ret.buildingNumber, ret.unitNumber, ret.roomNumber]
            ans_list.append(temp_arr)  # 添加当前数据进总list，最后转为csv

        df_to_csv = pd.DataFrame(ans_list, columns=['行政区划', '街路巷', '门牌', '栋楼', '单元号', '室号'])
        df_to_csv.to_csv(DATA_FILE_PATH + 'sc' + fileName, index=False, sep=',',
                         encoding='utf_8_sig')  # 先转 dataframe,再转 csv

    @staticmethod
    def train(filename):
        """

        :param self:
        :param filename:
        :return:
        """
        model = AddressMatchingModel()  # 拿模型
        train = AddressMatchingModelTrain(filename)  # new 一个训练类
        train.train(model)
        model.save()


if __name__ == '__main__':
    # print(DATA_FILE_PATH)
    if sys.argv[1] == '1':
        try:
            AddressMatching.train(sys.argv[2])
            print("训练成功！")
        except:
            print("错误！")

    elif sys.argv[1] == '2':
        print(AddressMatching.once_processing(sys.argv[2]))
    elif sys.argv[1] == '3':
        try:
            AddressMatching.many_times_processing(sys.argv[2])
            print("批量操作成功！")
        except:
            print("错误！")
